﻿var searchKey;
var searchWords = new Array();
var selectedSong;
var songs;
var secondTry = false;

var wordType = "synonym";
var wordnikApiKey = "19aee7e5807d0af56e00b0a66e50b19274930c2f2acce18f7";
var wordnikBaseUrl = "http://api.wordnik.com/v4/word.json/";
var wordnikLimit = 3;

var musixmatchBaseUrl = "http://api.musixmatch.com/ws/1.1/track.search";
var musixmatchApiKey = "ef2d6589f5ecbd5af6974490547c51a0";
var quorumFactor;
var musixmatchPageSize = 30;

function searchSongs(e) {
	searchKey = $('input').textinput().val();
	if(searchKey.trim() == undefined || searchKey.trim() == "") {
		navigator.notification.beep(200);
		navigator.notification.alert("Don't fool me! :)");
		window.location = "index.html";
		return;
	}
	enlargeKey();
	e.preventDefault();
}

function enlargeKey() {
	searchWords[0] = searchKey;
	var url = wordnikBaseUrl + searchKey + "/related?useCanonical=true&limit=" + wordnikLimit + "&type=" + wordType + "&api_key=" + wordnikApiKey + "&callback=?";
	console.log(url);
	$.getJSON(url, wordnikSearchCallback);
}

function wordnikSearchCallback(data) {
	words = undefined;
	if(data[0] == undefined) {
		navigator.notification.beep(200);
		navigator.notification.alert("Too few results for this subject :(");
		window.location = "index.html";
		return;
	}
	words = data[0].words;
	searchWords[0] = searchKey;
	var musixmatchWord;
	musixmatchWord = searchKey;
    $.each(words, function(index, word) {
        searchWords[index+1] = word;
		musixmatchWord += "%20" + word;
    });
	musixmatchWord = musixmatchWord.replace(/ /g, "%20");
	quorumFactor = 1 / wordnikLimit;
	var musixmatchurl = musixmatchBaseUrl + "?apikey=" + musixmatchApiKey + "&format=jsonp&page_size=" + musixmatchPageSize + "&q_lyrics=" + musixmatchWord + "&quorum_factor=" + quorumFactor + "&callback=?";
	console.log(musixmatchurl);
	$.getJSON(musixmatchurl, musixmatchSearchCallback);
}

function musixmatchSearchCallback(data) {
	songs = data.message.body.track_list;
	var currentSong;
	var songlist = $('#songsList');
	if(songs.length == 0) {
		console.log("ciao");
	} else {
		$.each(songs, function(index, song) {
			currentSong = song.track;
			songlist.append('<li><a data-transition="none" href="song.html" onClick="selectedSong =' + currentSong.track_id + ';">' +
			'<img src="' + currentSong.album_coverart_100x100 + '" class="list-icon">' +                       
			'<h4>' + currentSong.track_name + '</h4>' +
			'<p>' + currentSong.artist_name + '</p>' +
			'</li></li>');
		});
		songlist.listview('refresh');
	}
}

